using System;
using System.Collections.Generic;
using System.Linq;
public class Card {
    public int[] CardArr = new int[54];//54张牌
    /// <summary>
    /// 初始化一副牌
    /// </summary>
    public Card() {
        for (int num=0;num< CardArr.Length;num++) {
            CardArr[num] = num + 1;

        }
    }

}
//房间
public class Room
{
    //状态
    public enum Status
    {
        Prepare = 1,//准备
        Fight = 2,//战斗
    }
    public Status status = Status.Prepare;//默认是在准备中
                                          //玩家
    public int maxPlayers = 3;//房间人数
    public Dictionary<string, Player> list = new Dictionary<string, Player>();


    //添加玩家
    public bool AddPlayer(Player player)
    {
        lock (list)
        {
            if (list.Count >= maxPlayers)
                return false;
            PlayerTempData tempData = player.tempData;
            tempData.room = this;
            //tempData.team = SwichTeam ();
            tempData.status = PlayerTempData.Status.Room;

            if (list.Count == 0) { tempData.isOwner = true; }
            string id = player.id;
            list.Add(id, player);
        }
        return true;
    }

    ////分配队伍
    //public int SwichTeam()
    //{
    //	int count1 = 0;
    //	int count2 = 0;
    //	foreach(Player player in list.Values)
    //	{
    //		if(player.tempData.team == 1) count1++;
    //		if(player.tempData.team == 2) count2++;
    //	}
    //	if (count1 <= count2)
    //		return 1;
    //	else
    //		return 2;
    //}

    //删除玩家
    public void DelPlayer(string id)
    {
        lock (list)
        {
            if (!list.ContainsKey(id))
                return;
            bool isOwner = list[id].tempData.isOwner;
            list[id].tempData.status = PlayerTempData.Status.None;
            list.Remove(id);
            if (isOwner)
                UpdateOwner();
        }
    }

    //更换房主
    public void UpdateOwner()
    {
        lock (list)
        {
            if (list.Count <= 0)
                return;

            foreach (Player player in list.Values)
            {
                player.tempData.isOwner = false;
            }

            Player p = list.Values.First();
            p.tempData.isOwner = true;
        }
    }

    //广播
    public void Broadcast(ProtocolBase protocol)
    {
        foreach (Player player in list.Values)
        {
            player.Send(protocol);
        }
    }

    //房间信息
    public ProtocolBytes GetRoomInfo()
    {
        ProtocolBytes protocol = new ProtocolBytes();
        protocol.AddString("GetRoomInfo");
        //房间信息
        protocol.AddInt(list.Count);
        //每个玩家信息
        foreach (Player p in list.Values)
        {
            protocol.AddString(p.id);
            protocol.AddInt(p.tempData.team);
            protocol.AddInt(p.data.win);
            protocol.AddInt(p.data.fail);
            int isOwner = p.tempData.isOwner ? 1 : 0;
            protocol.AddInt(isOwner);
        }
        return protocol;
    }

    /// <summary>
    /// 房间是否可以开战（遍历玩家数组判断的是红蓝双方的人数是不是都大于1）
    /// </summary>如果双方都大于1就开战
    /// <returns></returns>
    //public bool CanStart()
    //{
    //	if (status != Status.Prepare)
    //		return false;

    //	int count1 = 0;
    //	int count2 = 0;

    //	foreach(Player player in list.Values)
    //	{
    //		if(player.tempData.team == 1) count1++;
    //		if(player.tempData.team == 2) count2++;
    //	}

    //       if (count1 < 1 || count2 < 1)
    //           return false;

    //	return true;
    //}

    ///判断是否可以战斗（检测他的状态是否在准备中，然后判断玩家是否是满三个人）
    public bool CanStart()
    {
        if (status != Status.Prepare)
            return false;
        if (list.Count == 3)
        { return true; }
        return false;
    }
    /// <summary>
    /// 开始游戏
    /// </summary>
    public void StartFight()
    {
        //ProtocolBytes protocol = new ProtocolBytes();
        //protocol.AddString("Fight");
        int cont = 0;
        status = Status.Fight;//状态等于战斗状态
        lock (list)
        {
            //protocol.AddInt(list.Count);
            //Card L_card= ShuffleCard(53);
           ShuffleCard(53);
            List<string> test = new List<string>(list.Keys);
            for (int p=0;p<list.Count;p++) {
                ProtocolBytes protocol = new ProtocolBytes();
                protocol.AddString("Fight");
                protocol.AddInt(list.Count);
                Console.WriteLine("遍历玩家的次数！！！！" + list.Count+"id 是"+ list[test[p]].id.ToString());
                protocol.AddString(list[test[p]].id.ToString());
                for (int s = cont * 17; s < 17 * (cont + 1); s++)
                {
                    //cardnums[s] = L_card.CardArr[s];
                    Console.Write("[警告]玩家遍历的牌是" + card.CardArr[s]);
                    protocol.AddInt(card.CardArr[s]);
                }
                
                list[test[p]].tempData.status = PlayerTempData.Status.Fight;
                cont = cont + 1;
                list[test[p]].Send(protocol);
            }
            //foreach (Player p in list.Values)
            //{
            //    Console.WriteLine("遍历玩家的次数！！！！"+ list.Count);
            //    protocol.AddString(p.id);//人物id（名字）

            //    //int[] cardnums=new int[17];
            //    for (int s= cont*17; s<17*(cont+1);s++) {
            //        //cardnums[s] = L_card.CardArr[s];
            //        Console.Write("[警告]玩家遍历的牌是"+ card.CardArr[s]);
            //        protocol.AddInt(card.CardArr[s]);
            //    }
            //    //p.tempData.L_card = cardnums;
            //    //p.tempData.hp = 200;
               
            //    //p.Send(protocol);

            //    //for (int i = 0; i < L_card.CardArr.Length; i++) {

            //    //    protocol.AddInt(L_card.CardArr[i]);
            //    //}

            //    p.tempData.status = PlayerTempData.Status.Fight;
            //    cont = cont + 1;
            //}
            //Broadcast(protocol);
        }
    }
    /// <summary>
    /// 洗牌
    /// </summary>
    ///     
   private Card card = new Card();
    Card ShuffleCard(int num){
        Random ran = new Random();
        for (int i=num-1;num>=1;num--) {
            int rand = ran.Next(1,53);
            Console.WriteLine("随机的数"+ rand);
            MySwap( i, rand,card);
        }
        return card;
    }
    /// <summary>
    /// 交换值
    /// </summary>
    /// <param name="x">下标</param>
    /// <param name="y">随机的下标</param>
    /// <param name="ca">要互换的数组</param>
    void MySwap( int x, int y, Card ca)
    {  
        int temp = ca.CardArr[x];
        ca.CardArr[x] = ca.CardArr[y];
        ca.CardArr[y] = temp;
        Console.WriteLine("[警告]交换值");
    }
//public void StartFight()
//{
//    ProtocolBytes protocol = new ProtocolBytes();
//    protocol.AddString("Fight");
//    status = Status.Fight;
//    int teamPos1 = 1;
//    int teamPos2 = 1;
//    lock (list)
//    {
//        protocol.AddInt(list.Count);
//        foreach (Player p in list.Values)
//        {
//            p.tempData.hp = 200;
//            protocol.AddString(p.id);
//            protocol.AddInt(p.tempData.team);
//            if (p.tempData.team == 1)
//                protocol.AddInt(teamPos1++);
//            else
//                protocol.AddInt(teamPos2++);

//            p.tempData.status = PlayerTempData.Status.Fight;
//        }
//        Broadcast(protocol);
//    }
//}

//胜负判断
private int IsWin()
	{
		if (status != Status.Fight)
			return 0;
		
		int count1 = 0;
		int count2 = 0;
		foreach(Player player in list.Values)
		{
			PlayerTempData pt = player.tempData;
			if(pt.team == 1 && pt.hp > 0) count1++;
			if(pt.team == 2 && pt.hp > 0) count2++;
		}
		
		if(count1 <= 0) return 2;
		if(count2 <= 0) return 1;
		return 0;
	}


	public void UpdateWin()
	{
		int isWin = IsWin();
		if (isWin == 0)
			return;
		//改变状态 数值处理
		lock (list) 
		{
			status = Status.Prepare;
			foreach (Player player in list.Values) 
			{
				player.tempData.status = PlayerTempData.Status.Room;
				if (player.tempData.team == isWin)
					player.data.win++;
				else
					player.data.fail++;
			}
		}
		//广播
		ProtocolBytes protocol = new ProtocolBytes();
		protocol.AddString ("Result");
		protocol.AddInt (isWin);
		Broadcast (protocol);
	}


	//中途退出战斗
	public void ExitFight(Player player)
	{
		//摧毁坦克
		if (list [player.id] != null)
			list [player.id].tempData.hp = -1;
		//广播消息
		ProtocolBytes protocolRet = new ProtocolBytes();
		protocolRet.AddString ("Hit");
		protocolRet.AddString (player.id);
		protocolRet.AddString (player.id);
		protocolRet.AddFloat (999);
		Broadcast (protocolRet);
		//增加失败次数
		if (IsWin () == 0)
			player.data.fail++;
		//胜负判断
		UpdateWin();
	}
}